package com.lh.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lh.base.ResResult;
import com.lh.base.ResResultCode;
import com.lh.constant.Constant;
import com.lh.exception.BizException;
import com.lh.pojo.SysUser;
import com.lh.mapper.SysUserMapper;
import com.lh.pojo.User;
import com.lh.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.util.JwtUtils;
import com.lh.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lh
 * @since 2021-03-02
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private RedisUtil redisUtil;
    @Value("${privateKey}")
    private String privateKey;

    @Override
    public ResResult userLogin(SysUser sysUser) {
        if (StrUtil.isEmpty(sysUser.getUsername()) || StrUtil.isEmpty(sysUser.getPassword())) {
            return ResResult.failure(ResResultCode.BIZ_ERROR);
        }
        // hutool提供的工具类 创建RSA加密对象 私钥key作为参数
        RSA rsa = new RSA(privateKey);
        // 私钥解密
        String username = rsa.decryptStr(sysUser.getUsername(), KeyType.PrivateKey);
        String password = rsa.decryptStr(sysUser.getPassword(), KeyType.PrivateKey);
        log.info("解密后用户名:" + username);
        log.info("解密后密码:" + password);
        // 验证用户
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        sysUser = this.getOne(wrapper);
        if (sysUser == null) {
            return ResResult.failure(ResResultCode.USERNAME_OR_PASSWORD_ERROR);
        }
        // 验证密码
        if (!DigestUtil.bcryptCheck(password, sysUser.getPassword())) {
            return ResResult.failure(ResResultCode.USERNAME_OR_PASSWORD_ERROR);
        }
        // 判断用户是否被禁用
        if (sysUser.getLocked().equals("1")) {
            return ResResult.failure(ResResultCode.ACCOUNT_DISABLE);
        }

        // 生成token放入Redis
        String token = JwtUtils.sign(sysUser.getUsername(), sysUser.getPassword());
        redisUtil.set(Constant.LOGIN_PREFIX + sysUser.getId(), token, Constant.TOKEN_EXPIRE);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);

        return ResResult.success(map);
    }
}
